<template>
  <div  @drop.prevent="onDrop" :style="{boxShadow:active?'inset 0 0 8px var(--pc)':'',cursor:uploading?'wait':'default'}" @dragover.prevent @dragenter="onDragEnter" @dragleave="onDragLeave">
    <slot></slot>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import { loadingBar,message } from 'HeyUI';

const props=defineProps({
  //支持的后缀类型*.jpg,*.xx
  accept: {
    type: String
  }
})
const emit=defineEmits(["drop"])
const active=ref(false)
const uploading=ref(false)

function onDrop(e){
  active.value=false
  if(e.dataTransfer.files.length>1){
    message({type: 'error', text: '不支持多个文件'})
    return
  }
  for (let file of e.dataTransfer.files) {
    // if (file.type == '') {
    //   message({type: 'error', text: '不支持的文件"' + file.name + '"'})
    //   return
    // }
    if (filterType(file.name)) {
      message({type: 'warn', text: '不支持的文件"' + file.name + '"'})
      continue
    }
  }
  uploading.value=true
  loadingBar.start();
  const data={
    file:e.dataTransfer.files[0],
    success(){
      uploading.value=false
      loadingBar.success()
    },fail(){
      uploading.value=false
      loadingBar.fail()
    }
  }
  emit("drop",data)
}
function onDragEnter(e){
  active.value=true
}
function onDragLeave(e){
  active.value=false
}
function filterType(name) {
  if (!props.accept) {
    return false
  }
  let type = name.substring(name.lastIndexOf("."));
  if (props.accept.indexOf(type) == -1) {
    return true
  }
  return false
}
</script>
